package org.example.netty.socketTest;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

public class SocketClient {
    public static void main(String[] args) throws InterruptedException {
        Channel channel = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                //客户端使用handler处理数据
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(
                                //解码
                                new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,
                                        0,4,0,4)
                        );
                        //编码
                        socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
                        //解码
                        socketChannel.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
                        //编码
                        socketChannel.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));

                        socketChannel.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
                                System.out.println("client output: "+s);
                            }
                        });
                    }
                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        cause.printStackTrace();
                        ctx.close();
                    }
                })
                .connect(new InetSocketAddress("localhost", 8888))
                .sync()
                .channel();
        System.out.println(channel);
        System.out.println("111");
    }
}
